<template>
	<div class="suggesstionContainer">
		<van-cell v-for="(item,index) in suggesstions" 
		:key="item" 
		icon="search"
		@click="$emit('search',item)"
		>
			<div slot="title" v-html="htmlStr(item)" ></div>
		</van-cell>
	</div>
</template>

<script>
	import {getSuggesstions} from '@/api/search.js'
	const debounce = function(fn,delay){
		let timer = null;
		return function(...args){
			if(timer) clearTimeout(timer)
			timer = setTimeout(()=>{
				fn.apply(this,args)
			},delay)
		}
	}
	export default {
		name:"suggesstion",
		props:{
			q:{
				type:String,
				required:true
			}
		},
		data(){
			return {
				suggesstions:[]
			}
		},
		methods:{
			htmlStr(sugText){
				const reg = new RegExp(this.q,'gi')
				return sugText.replace(reg,`<span style="color:red">${this.q}</span>`)
				
			}
		},
		watch:{
			q:{
				handler:debounce(async function(){
					let q = this.q 
					const {data} = await getSuggesstions(q)
					this.suggesstions = data.data.options
				},500),
				immediate:true
			}
		}
	}
</script>

<style scoped lang="less">
</style>
